package com.small.controller.backend;

import com.google.common.collect.Maps;
import com.small.common.Const;
import com.small.common.ResponseCode;
import com.small.common.ServerResponse;
import com.small.pojo.Product;
import com.small.pojo.User;
import com.small.service.IFileService;
import com.small.service.IProductService;
import com.small.service.IUserService;
import com.small.util.CookieUtil;
import com.small.util.JsonUtil;
import com.small.util.PropertiesUtil;
import com.small.util.RedisShradedPoolUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * @program: small
 * @description:管理员商品操作
 * @author: Mr.Xie
 * @create: 2019-04-25 08:52
 */
@Controller
@RequestMapping("/manage/product")
@Slf4j
public class ProductManageContoller {

    @Autowired
    private IUserService iUserService;
    @Autowired
    private IProductService iProductService;
    @Autowired
    private IFileService iFileService;

    //添加或者更新商品
    @RequestMapping("save.do")
    @ResponseBody
    public ServerResponse productSave(HttpServletRequest request, Product product){
//        String loginToken = CookieUtil.readLoginToken(request);
//        if (StringUtils.isEmpty(loginToken)) {
//            return ServerResponse.createBySuccessMessage("用户未登录");
//        }
//        String userJsonstr = RedisShradedPoolUtil.get(loginToken);
//        User user = JsonUtil.string2Obj(userJsonstr, User.class);
//        if(user==null){
//            return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(),"用户未登录，请登录");
//        }
//        if(iUserService.checkAdminRole(user).isSuccess()){
//            return iProductService.saveOrUpdateProduct(product);
//        }else {
//            return ServerResponse.createByErrorMessage("无权限操作");
//        }
        return iProductService.saveOrUpdateProduct(product);
    }
    //设置商品的状态（上架，下架，删除）
    @RequestMapping("set_sale_status.do")
    @ResponseBody
    public ServerResponse setSaleStatus(HttpServletRequest request, Integer productId,Integer status){
//        String loginToken = CookieUtil.readLoginToken(request);
//        if (StringUtils.isEmpty(loginToken)) {
//            return ServerResponse.createBySuccessMessage("用户未登录");
//        }
//        String userJsonstr = RedisShradedPoolUtil.get(loginToken);
//        User user = JsonUtil.string2Obj(userJsonstr, User.class);
//        if(user==null){
//            return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(),"用户未登录，请登录");
//        }
//        if(iUserService.checkAdminRole(user).isSuccess()){
//            return iProductService.setSaleStatus(productId,status);
//        }else {
//            return ServerResponse.createByErrorMessage("无权限操作");
//        }
        return iProductService.setSaleStatus(productId,status);
    }

    //获取商品详情
    @RequestMapping("detail.do")
    @ResponseBody
    public ServerResponse getDetail(HttpServletRequest request, Integer productId){
//        String loginToken = CookieUtil.readLoginToken(request);
//        if (StringUtils.isEmpty(loginToken)) {
//            return ServerResponse.createBySuccessMessage("用户未登录");
//        }
//        String userJsonstr = RedisShradedPoolUtil.get(loginToken);
//        User user = JsonUtil.string2Obj(userJsonstr, User.class);
//        if(user==null){
//            return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(),"用户未登录，请登录");
//        }
//        if(iUserService.checkAdminRole(user).isSuccess()){
//            return iProductService.manageProductDetail(productId);
//        }else {
//            return ServerResponse.createByErrorMessage("无权限操作");
//        }
        return iProductService.manageProductDetail(productId);
    }

    //商品分页
    @RequestMapping("list.do")
    @ResponseBody
    public ServerResponse getList(HttpServletRequest request, @RequestParam(value = "pageNum",defaultValue = "1") int pageNum,@RequestParam(value = "pageSize",defaultValue = "10") int pageSize){
//        String loginToken = CookieUtil.readLoginToken(request);
//        if (StringUtils.isEmpty(loginToken)) {
//            return ServerResponse.createBySuccessMessage("用户未登录");
//        }
//        String userJsonstr = RedisShradedPoolUtil.get(loginToken);
//        User user = JsonUtil.string2Obj(userJsonstr, User.class);
//        if(user==null){
//            return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(),"用户未登录，请登录");
//        }
//        if(iUserService.checkAdminRole(user).isSuccess()){
//            return iProductService.getProductList(pageNum,pageSize);
//        }else {
//            return ServerResponse.createByErrorMessage("无权限操作");
//        }
        return iProductService.getProductList(pageNum,pageSize);
    }
    //商品查找
    @RequestMapping("search.do")
    @ResponseBody
    public ServerResponse productSearch(HttpServletRequest request, String productName,Integer productId,@RequestParam(value = "pageNum",defaultValue = "1") int pageNum,@RequestParam(value = "pageSize",defaultValue = "10") int pageSize){
//        String loginToken = CookieUtil.readLoginToken(request);
//        if (StringUtils.isEmpty(loginToken)) {
//            return ServerResponse.createBySuccessMessage("用户未登录");
//        }
//        String userJsonstr = RedisShradedPoolUtil.get(loginToken);
//        User user = JsonUtil.string2Obj(userJsonstr, User.class);
//        if(user==null){
//            return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(),"用户未登录，请登录");
//        }
//        if(iUserService.checkAdminRole(user).isSuccess()){
//            return iProductService.searchProduct(productName,productId,pageNum,pageSize);
//        }else {
//            return ServerResponse.createByErrorMessage("无权限操作");
//        }
        return iProductService.searchProduct(productName,productId,pageNum,pageSize);
    }
    //图片上传
    @RequestMapping("upload.do")
    @ResponseBody
    public ServerResponse upload(@RequestParam(value = "upload_file",required = false) MultipartFile file, HttpServletRequest request){
//        String loginToken = CookieUtil.readLoginToken(request);
//        if (StringUtils.isEmpty(loginToken)) {
//            return ServerResponse.createBySuccessMessage("用户未登录");
//        }
//        String userJsonstr = RedisShradedPoolUtil.get(loginToken);
//        User user = JsonUtil.string2Obj(userJsonstr, User.class);
//        if(user==null){
//            return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(),"用户未登录，请登录");
//        }
//        if(iUserService.checkAdminRole(user).isSuccess()){
//            //设置tomcat上传路径
//            String path = request.getSession().getServletContext().getRealPath("upload");
//            //完成ftp文件上传
//            String targetFileName = iFileService.upload(file, path);
//            //ftp上传路径返回给前台
//            String url= PropertiesUtil.getProperty("ftp.server.http.prefix")+targetFileName;
//            log.info("上传的路径："+url);
//            //存入文件名和ftp访问路径
//            Map fileMap= Maps.newHashMap();
//            fileMap.put("uri",targetFileName);
//            fileMap.put("url",url);
//            //返回给前台
//            return ServerResponse.createBySuccess(fileMap);
//        }else {
//            return ServerResponse.createByErrorMessage("无权限操作");
//        }

        //设置tomcat上传路径
        String path = request.getSession().getServletContext().getRealPath("upload");
        //完成ftp文件上传
        String targetFileName = iFileService.upload(file, path);
        //ftp上传路径返回给前台
        String url= PropertiesUtil.getProperty("ftp.server.http.prefix")+targetFileName;
        Map fileMap= Maps.newHashMap();
        fileMap.put("uri",targetFileName);
        fileMap.put("url",url);
        //返回给前台
        return ServerResponse.createBySuccess(fileMap);
    }
    //富文本上传
    @RequestMapping("richtext_img_upload.do")
    @ResponseBody
    public Map richtextImgUpload(HttpSession session, @RequestParam(value = "upload_file",required = false) MultipartFile file, HttpServletRequest request, HttpServletResponse response){
        Map resultmap=Maps.newHashMap();
//        String loginToken = CookieUtil.readLoginToken(request);
//        if (StringUtils.isEmpty(loginToken)) {
//            resultmap.put("error",false);
//            resultmap.put("msg","请登录");
//            return resultmap;
//        }
//        String userJsonstr = RedisShradedPoolUtil.get(loginToken);
//        User user = JsonUtil.string2Obj(userJsonstr, User.class);
//        if(user==null){
//            resultmap.put("success",false);
//            resultmap.put("msg","请登录管理员");
//            return resultmap;
//
//        }
//        if(iUserService.checkAdminRole(user).isSuccess()){
//            String path = request.getSession().getServletContext().getRealPath("upload");
//            String targetFileName = iFileService.upload(file, path);
//            if(StringUtils.isBlank(targetFileName)){
//                resultmap.put("success",false);
//                resultmap.put("msg","上传失败");
//                return resultmap;
//            }
//            String url= PropertiesUtil.getProperty("ftp.server.http.prefix")+targetFileName;
//            resultmap.put("success",true);
//            resultmap.put("msg","上传成功");
//            resultmap.put("file_path",url);
//            response.addHeader("Access-Control-Allow-Headers","X-File-Name");
//            return resultmap;
//
//        }else {
//            resultmap.put("success",false);
//            resultmap.put("msg","无权限操作");
//            return resultmap;
//        }
        //设置上传路径
        String path = request.getSession().getServletContext().getRealPath("upload");
        String targetFileName = iFileService.upload(file, path);
        if(StringUtils.isBlank(targetFileName)){
            resultmap.put("error",false);
            resultmap.put("msg","上传失败");
            return resultmap;
        }

        String url= PropertiesUtil.getProperty("ftp.server.http.prefix")+targetFileName;
        resultmap.put("success",true);
        resultmap.put("msg","上传成功");
        resultmap.put("file_path",url);
        response.addHeader("Access-Control-Allow-Headers","X-File-Name");
        return resultmap;
    }
}
